package cn.topevery.garden.dal.logic;

import cn.hutool.core.bean.BeanUtil;
import cn.topevery.garden.dal.dao.GreTreeDao;
import cn.topevery.garden.dal.util.ExcelImportUtil;
import cn.topevery.garden.entity.po.GreTree;
import cn.topevery.garden.entity.query.GreTreeQuery;
import cn.topevery.garden.entity.vo.GreTreeRecordVO;
import cn.topevery.garden.entity.vo.GreTreeVO;
import cn.topevery.garden.framework.base.BaseLogic;
import hw.topevery.basis.dal.logic.SysDictLogic;
import hw.topevery.basis.dal.util.SysMapTreeUtil;
import hw.topevery.basis.entity.fetch.DictFetch;
import hw.topevery.basis.entity.po.SysDict;
import hw.topevery.basis.runtime.UserRuntime;
import hw.topevery.framework.GeometryHelper;
import hw.topevery.framework.db.base.BaseEntityDao;
import hw.topevery.framework.db.entity.DataPager;
import hw.topevery.framework.web.JsonResult;
import org.apache.commons.lang.StringUtils;
import org.locationtech.jts.geom.Geometry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;

/**
 * 行道树
 *
 * @author code-generate
 * @date 2022-01-05
 */
@Service
public class GreTreeLogic extends BaseLogic<GreTree> {
    @Autowired
    GreTreeDao greTreeDao;

    @Override
    public BaseEntityDao<GreTree, Integer> getDao() {
        return greTreeDao;
    }


    /**
     * 获取列表
     *
     * @param query
     */
    public DataPager<GreTreeVO> listPage(GreTreeQuery query) {
        return greTreeDao.listPage(query);
    }

    /**
     * 根据自增id批量删除
     *
     * @param ids
     */
    public void deleteBatchById(String userId, Integer[] ids) {
        greTreeDao.delete(userId, ids);
    }

    /**
     * 根据自增id保存或者更新
     *
     * @param greTree 实体
     */
    public void saveOrUpdate(String userId, GreTree greTree) {
        greTreeDao.saveOrUpdate(userId, greTree);
    }

    /**
     * 根据自定义列值来获取对象
     */
    public GreTree getEntityByColumn(String key, String value) {
        return greTreeDao.getEntityByColumn(key, value);
    }

    public DataPager<GreTreeVO> getList(GreTreeQuery query) {
        return greTreeDao.getList(query);
    }

    public DataPager<GreTreeRecordVO> getRecordList(GreTreeQuery query) {
        return greTreeDao.getRecordList(query);
    }

    public void update(GreTree getGreTree, Integer userId) {
        greTreeDao.update(getGreTree, userId);
    }

    public void insert(GreTree greTree, Integer userId) {
        greTreeDao.insert(greTree, userId);
    }

    public void deleteByIds(List<String> ids) {
        greTreeDao.deleteByIds(ids);
    }

    public void deleteById(Integer id) {
        greTreeDao.deleteById(id);
    }

    public List<Map<String, Object>> getAllTreeForMap(String type) {
        return greTreeDao.getAllTreeForMap(type);
    }

    public void insertSql(GreTree greTree) {
        greTreeDao.insertSql(greTree);
    }

    @Autowired
    private SysMapTreeUtil sysMapTreeUtil;

    @Resource
    private SysDictLogic sysDictLogic;

    public JsonResult<?> analysisExcel(MultipartFile file) {
        try {
            Map<String, Object> map = ExcelImportUtil.analysisExcel(file.getInputStream(), GreTreeVO.class, filterFunc());
            return JsonResult.ok(map);
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.error("解析发生错误，请按照模板格式填写数据！");
        }
    }

    private Predicate<GreTreeVO> filterFunc() {
        return vo -> {
            if (StringUtils.isBlank(vo.getCode()) || StringUtils.isBlank(vo.getName())
                    || StringUtils.isBlank(vo.getDistractName())) {
                vo.setErrorMessage("编号、名称、区域不能为空\t");
                return true;
            }
            if (vo.getLng() != null && vo.getLat() != null) {
                String wkt = "POINT(" + vo.getLng() + " " + vo.getLat() + ")";
                Geometry geometry = GeometryHelper.getGeometry(wkt);//检查坐标是否存在问题
            }
            //校验行政区域
            StringBuilder errorMessageBuilder = new StringBuilder();
            boolean areaFlag = ExcelImportUtil.verifyArea(vo, errorMessageBuilder, sysMapTreeUtil);
            //生长状态
            if (StringUtils.isNotBlank(vo.getGrowthState())) {
                DictFetch dictFetch = new DictFetch();
                dictFetch.setNsId("a5b33920-9284-4549-b5cf-c18a959efc2a");
                List<SysDict> listDict = sysDictLogic.getListDict(dictFetch);
                long count = listDict.stream().filter(f -> f.dictName.equals(vo.getGrowthState())).count();
                if (count < 1) {
                    errorMessageBuilder.append("生长状态填写有误！");
                    return true;
                }
            }
            return areaFlag;
        };
    }

    public JsonResult<?> importExcel(List<GreTreeVO> greTreeVOList) {
        return ExcelImportUtil.importExcel(greTreeVOList, filterFunc(), vo -> {
                    GreTree greTree = BeanUtil.copyProperties(vo, GreTree.class);
                    if (greTree.getLng() != null && greTree.getLat() != null) {
                        String wkt = "POINT(" + greTree.getLng() + " " + greTree.getLat() + ")";
                        Geometry geometry = GeometryHelper.getGeometry(wkt);
                        greTree.setMapRanges(geometry);
                        greTree.setGeoWkt(wkt);
                    }
                    return greTree;
                },
                entities -> greTreeDao.insert(UserRuntime.getSysUser().id.toString(), entities));
    }
}
